import { request } from '../../request/index'
import { showToast } from '../../utils/asyncWX'
Page({
  data: {
    goodDetail: {},
    isStar: false
  },
  GoodInfo: {},
  onShow() {
    const { gid } = getCurrentPages().splice(-1)[0].options
    this.getGoodDetail(gid)
  },
  async getGoodDetail(id) {
    const { data: res } = await request({
      url: '/goods/detail',
      data: {
        goods_id: id
      }
    })
    if (res.meta.status !== 200) return
    this.GoodInfo = res.message
    let goodDetail = {
      goods_name: res.message.goods_name,
      goods_price: res.message.goods_price,
      goods_introduce: res.message.goods_introduce.replace(/\.webp/g, '.jpg'),
      pics: res.message.pics
    }
    let star = wx.getStorageSync('star') || []
    let isStar = star.some(item => item.goods_id === this.GoodInfo.goods_id)
    this.setData({
      goodDetail,
      isStar
    })
  },
  // 点击轮播图放大预览
  handelPrevewImage(e) {
    const urls = this.GoodInfo.pics.map(item => item.pics_mid)
    const { url: current } = e.currentTarget.dataset
    wx.previewImage({
      current,
      urls
    })
  },
  // 点击加入购物车
  handelCartAdd() {
    let cart = wx.getStorageSync('cart') || [];
    let index = cart.findIndex(item => item.goods_id === this.GoodInfo.goods_id)
    if (index === -1) {
      this.GoodInfo.num = 1
      this.GoodInfo.isChecked = true
      cart.push(this.GoodInfo)
    } else {
      // 数量加一
      cart[index].num++
    }
    wx.setStorageSync('cart', cart)
    wx.showToast({
      title: '加入购物车',
      icon: 'success',
      mask: true
    })
  },
  // 点击收藏
  starChange() {
    let star = wx.getStorageSync('star') || []
    const index = star.findIndex(item => item.goods_id === this.GoodInfo.goods_id)
    if (index > -1) {
      star.splice(index, 1)
      showToast({title: '取消收藏'})
    } else {
      star.push(this.GoodInfo)
      showToast({title: '收藏成功'})
    }
    wx.setStorageSync('star', star)
    this.setData({
      isStar: !this.data.isStar
    })
  }
})